package com.xhis.homenurse;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.idst.nls.internal.utils.L;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Poi;
import com.amap.api.navi.AmapNaviPage;
import com.amap.api.navi.AmapNaviParams;
import com.amap.api.navi.AmapNaviType;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.xhis.homenurse.tools.DialogTools;
import com.xhis.homenurse.views.ObservableWebView;
import com.xhis.homenurse.views.VpSwipeRefreshLayout;
import com.xhis.homenurse.webservice.api.ContactNet;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

public class MainActivity extends AppCompatActivity
{
    private SharedPreferences mSharedpreferences;
    //    WebView webview = null;
    ObservableWebView webview = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    private AMapLocation tempAMapLocation;
    private String TAG = "MainActivity";
    private AlertDialog dialog;
    private String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.CAMERA};
    //    private String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
//    private SwipeRefreshLayout mSwipeRefreshLayout;
    private VpSwipeRefreshLayout mSwipeRefreshLayout;
    private int OPEN_CAMERA = 789;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener()
    {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation)
        {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
//                    Toast.makeText(MainActivity.this,aMapLocation.getCity()+"  经度:"+aMapLocation.getLongitude()+
//                    "  维度:"+aMapLocation.getLatitude()+"  位置:"+aMapLocation.getAddress()+"  来源:"+aMapLocation.getLocationType()
//                    ,Toast.LENGTH_SHORT).show();
                    tempAMapLocation = aMapLocation;
                    Log.i("locationInfo", aMapLocation.getAddress() + "  " + aMapLocation.getCity());
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                    //当错误码是12或13时，表示app无定位权限，跳转到系统定位权限设置页，手动打开系统定位权限
                    if (aMapLocation.getErrorCode() == 12 || aMapLocation.getErrorCode() == 13) {
                        if (dialog == null || !dialog.isShowing()) {
                            showDialogLocationPermissionGoToAppSettting();
                        }
                    }
                }
            } else {
                Log.i("locationInfo2", "aMapLocation为空");
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mSharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);// wifi和gps同时，返回精度高的
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);// wifi定位，不使用gps
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //关闭缓存机制
//        mLocationOption.setLocationCacheEnable(false);
        //给客户端对象设置定位配置
        mLocationClient.setLocationOption(mLocationOption);
//        mLocationClient.startLocation();
        //设置全透明状态栏
        setStatusBarFullTransparent();
//      setFitSystemWindow(rootView,true);
        setContentView(R.layout.activity_main);
//        AndroidBug5497Workaround.assistActivity(this);
        initControl();
    }

    private void initControl()
    {
        webview = (ObservableWebView) findViewById(R.id.activity_main_webview);
        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setDomStorageEnabled(true);
//        settings.setAppCacheEnabled(false);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.addJavascriptInterface(this, "android");

        webview.loadUrl(getUrl());
        webview.setWebChromeClient(new FilePickWebChromeClient());
        webview.setWebViewClient(new FilePickWebViewClient());
        findViewById(R.id.textView1).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                startNavigation();
            }
        });
        findViewById(R.id.textView2).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                startNavigation(111.160448, 34.749495, "三门峡南站");
            }
        });
        mSwipeRefreshLayout = (VpSwipeRefreshLayout) findViewById(R.id.activity_main_swipeRefreshLayout);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.appColor, R.color.grey);//设置下拉刷新图案颜色
        mSwipeRefreshLayout.setEnabled(false);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
        {
            @Override
            public void onRefresh()
            {
                webview.reload();
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
//        webview.setOnScrollChangedCallback(new ObservableWebView.OnScrollChangedCallback()
//        {
//            public void onScroll(int dx, int dy, int dx_chage, int dy_change)
//            {
//                if (dy == 0){
//                    mSwipeRefreshLayout.setEnabled(true);
//                } else {
//                    mSwipeRefreshLayout.setEnabled(false);
//                }
//            }
//        });
    }

    //--------------------------开放接口，接受H5调用 start--------------------------------
    @JavascriptInterface
    public void startLocation()
    {
        try {
            Log.i("TAG", "startLocation");
            if (requestPermission()) {
                mLocationClient.startLocation();
            } else {
                startRequestPermission();
            }
//            mLocationClient.startLocation();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void stopLocation()
    {
        try {
            Log.i("TAG", "stopLocation");
            mLocationClient.stopLocation();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void getLocation(final String backInfo)
    {
        new Thread()
        {
            @Override
            public void run()
            {
                super.run();
                Log.i("TAG", "getLocation");
                String locationInfo = "";
                int times = 0;
                while (tempAMapLocation == null && times < 20) {
                    try {
                        times++;
                        sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                AMapLocation temp = tempAMapLocation;
                Log.i("TAG", "temp:" + ((temp == null) ? "temp为空" : temp.getAddress()));
                if (temp == null) {
                    locationInfo = "{\"code\":-1}";
                } else {
                    String address = null;
                    if (TextUtils.isEmpty(temp.getAddress())) {//解决gps定位只有经纬度的问题（oppo手机）
                        List<Address> addresses;
                        Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
                        try {
                            addresses = geocoder.getFromLocation(temp.getLatitude(), temp.getLongitude(), 1);
                            String city = addresses.get(0).getLocality();
                            String province = addresses.get(0).getAdminArea();
                            String getFeatureName = addresses.get(0).getFeatureName();
                            String getSubLocality = addresses.get(0).getSubLocality();

                            address = province + city + getSubLocality + getFeatureName;
                            L.e("选择地址", address);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        address = temp.getAddress();
                    }
                    locationInfo = "{\"code\":0,\"longitude\":\"" + temp.getLongitude() + "\",\"latitude\":\"" + temp.getLatitude() + "\"," +
                            "\"address\":\"" + address + "\",\"province\":\"" + temp.getProvince() + "\",\"city\":\"" + temp.getCity() + "\"," +
                            "\"district\":\"" + temp.getDistrict() + "\",\"street\":\"" + temp.getStreet() + "\",\"aoiname\":\"" + temp.getAoiName() + "\",\"poiname\":\"" + temp.getPoiName() + "\",\"info\":\"" + backInfo + "\"}";
                }
                if (webview != null) {
                    Log.i("TAG", "returnLocation:\n" + locationInfo);
                    final String finalLocationInfo = locationInfo;
                    webview.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            webview.loadUrl("javascript:receiveLocationInfo('" + finalLocationInfo + "')");
                        }
                    });
//                    webview.loadUrl("javascript:receiveLocationInfo('" + locationInfo + "')");
                }
            }
        }.start();
    }

    @JavascriptInterface
    public void startNavigation()
    {
        AmapNaviPage.getInstance().showRouteActivity(this, new AmapNaviParams(null), null);
    }

    @JavascriptInterface
    public void startNavigation(double longitude, double latitude, String address)
    {
        Poi start = null;
        if (tempAMapLocation != null) {
            start = new Poi("我的位置", new LatLng(tempAMapLocation.getLatitude(), tempAMapLocation.getLongitude()), "");
        }
//        Poi end = new Poi("目的地", new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)), "B000A83M61");
        if (TextUtils.isEmpty(address))
            address = "目的地";
        Poi end = new Poi(address, new LatLng(latitude, longitude), "");
        AmapNaviPage.getInstance().showRouteActivity(this, new AmapNaviParams(start, null, end, AmapNaviType.DRIVER), null);
    }

    @JavascriptInterface
    public void refreshListener(final boolean whetherRefresh)
    {
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                if (whetherRefresh) {
                    mSwipeRefreshLayout.setEnabled(true);
                } else {
                    mSwipeRefreshLayout.setEnabled(false);
                }
            }
        });
    }

    @JavascriptInterface
    public void goAppCamera()
    {
        if (requestCameraPermission()) {
            Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, OPEN_CAMERA);
        } else {
            startRequestPermission();
        }
    }

    @JavascriptInterface
    public void exitApp()
    {
        try {
            new AlertDialog.Builder(this).setIcon(R.mipmap.logo)
                    .setTitle("提示")
                    .setCustomTitle(DialogTools.getDialgoTitleView(this, "提示", R.mipmap.suredialog))
                    .setMessage("你确定要退出吗？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialog,
                                            int whichButton)
                        {
                            // finish掉当前页面；
                            finish();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//--------------------------开放接口，接受H5调用 end--------------------------------

    private String getUrl()
    {
        //https://m-nurse-nc-989.xiaohudaojia.com/
//        String url = mSharedpreferences.getString("url","https://m-patient.xiaohudaojia.com/");//患者端
        String urlParams = ContactNet.WEB_URL+ "?r=" + new Random().nextInt(9999) + "/";
        String url = mSharedpreferences.getString("url", urlParams);//护士端
        Log.i("URL", url);
        return url;
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        mLocationClient.stopAssistantLocation();
        stopLocation();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
//        boolean _ret = mEntryProxy.onActivityExecute(this, ISysEventListener.SysEventType.onKeyDown, new Object[] { keyCode, event });
//        return _ret ? _ret : super.onKeyDown(keyCode, event);
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            View view = getLayoutInflater().inflate(R.layout.dialog_address_setting, null);
            final EditText editText = view.findViewById(R.id.dialog_address_setting_addressEditText);
            editText.setText(getUrl());
            builder.setView(view);
            builder.setNegativeButton(getString(R.string.cancle), null);
            builder.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialogInterface, int i)
                {
                    mSharedpreferences.edit().putString("url", editText.getText().toString().trim()).commit();
                    webview.loadUrl(getUrl());
                }
            });
            builder.show();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webview.canGoBack()) {
                webview.goBack();//返回上一浏览页面
                return true;
            } else {
                new AlertDialog.Builder(this).setIcon(R.mipmap.logo)
                        .setTitle("提示")
                        .setCustomTitle(DialogTools.getDialgoTitleView(this, "提示", R.mipmap.suredialog))
                        .setMessage("你确定要退出吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog,
                                                int whichButton)
                            {
                                // finish掉当前页面；
                                finish();
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
                return true;
            }
//            webview.goBack();
//            return true;
        }
//        boolean _ret = mEntryProxy.onActivityExecute(this, ISysEventListener.SysEventType.onKeyUp, new Object[] { keyCode, event });
//        return _ret ? _ret : super.onKeyUp(keyCode, event);
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event)
    {
//        boolean _ret = mEntryProxy.onActivityExecute(this, ISysEventListener.SysEventType.onKeyLongPress, new Object[] { keyCode, event });
//        return _ret ? _ret : super.onKeyLongPress(keyCode, event);
        return super.onKeyLongPress(keyCode, event);
    }

    public void onConfigurationChanged(Configuration newConfig)
    {
        if (newConfig.fontScale != 1)//非默认值
            getResources();
        try {
            int temp = this.getResources().getConfiguration().orientation;

            super.onConfigurationChanged(newConfig);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //系统字体变大导致的布局异常
    @Override
    public Resources getResources()
    {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) {//非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }


    protected void setStatusBarFullTransparent()
    {
        if (Build.VERSION.SDK_INT >= 21) {//21表示5.0
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //虚拟键盘也透明
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
    }

    protected void setFitSystemWindow(View view, boolean fitSystemWindow)
    {
        if (view == null) {
            view = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
        }
        view.setFitsSystemWindows(fitSystemWindow);

    }

    //两个处理文件选择后回调给web的变量
    ValueCallback<Uri> mUploadMessage;
    ValueCallback<Uri[]> mFilePathCallback;

    public class FilePickWebChromeClient extends WebChromeClient
    {
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams)
        {
            if (mFilePathCallback != null)
                return true;
            mFilePathCallback = filePathCallback;//一个回调的初始化
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //如果选择的是拍照，这个值应该是类似这种image/jpeg,image/jpg,image/gif,image/png,image/bmp，所以我选择了判断包含
                if (fileChooserParams.isCaptureEnabled()) {//打开相机
                    return true;//h5调用android写的方法获取相机
                } else if (fileChooserParams.getAcceptTypes()[0].contains("image")) {
                    selectImage();//选择图片
                } else {
                    selectFile();//选择文件
                }
            }
            return true;
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType)
        {
            //此处同以上
            if (mUploadMessage != null)
                return;
            mUploadMessage = uploadMsg;//另一个回调的初始化
            if (!TextUtils.isEmpty(acceptType) && acceptType.contains("image")) {
                selectImage();
            } else {
                selectFile();
            }
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg)
        {
            openFileChooser(uploadMsg, "");
        }

        // For Android  > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
        {
            //此处同以上
            if (mUploadMessage != null)
                return;
            mUploadMessage = uploadMsg;//另一个回调的初始化
//            Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//            startActivityForResult(intent, OPEN_CAMERA);

//            openFileChooser(uploadMsg, acceptType);
        }

        public static final int REC_REQUESTCODE = 1;

        //选择文件 开始调用系统的文件选择器
        private void selectFile()
        {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");//这个是所有类型文件的筛选 如果只想要图片可以设置image/*   网上有各种文件类型的说明，可以根据自己的需要配置
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, REC_REQUESTCODE);
        }

        //选择图片 开始调用系统的文件选择器
        private void selectImage()
        {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");//这个是所有类型文件的筛选 如果只想要图片可以设置image/*   网上有各种文件类型的说明，可以根据自己的需要配置
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, REC_REQUESTCODE);
        }

        @Override
        public void onProgressChanged(WebView webView, int i)
        {
            super.onProgressChanged(webView, i);
            if (i == 100) {

            }
        }
    }

    public class FilePickWebViewClient extends com.tencent.smtt.sdk.WebViewClient
    {
        @Override
        public void onReceivedSslError(WebView webView, com.tencent.smtt.export.external.interfaces.SslErrorHandler sslErrorHandler, com.tencent.smtt.export.external.interfaces.SslError sslError)
        {
            sslErrorHandler.proceed();
            super.onReceivedSslError(webView, sslErrorHandler, sslError);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView wv, String url)
        { // 解决打电话出现net::ERR_UNKNOWN_URL_SCHEME和微信支付的问题
            if (url == null) return false;
            try {
                if (url.startsWith("weixin:") //微信
                        || url.startsWith("alipays:") //支付宝
                        || url.startsWith("mailto:") //邮件
                        || url.startsWith("tel:")
                        || url.startsWith("qqmap://map/routeplan")
                        || url.startsWith("qqmap://map/maphome")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                } else if (url.startsWith("https://wx.tenpay.com")) { //微信支付信息url加上Referer并重新加载获取唤起url
                    if (("4.4.3" == android.os.Build.VERSION.RELEASE) || ("4.4.4" == android.os.Build.VERSION.RELEASE)) {
                        //兼容这两个版本设置referer无效的问题
                        wv.loadDataWithBaseURL("https://m-patient.xiaohudaojia.com",
                                "<script>window.location.href=\"$reloadUrl\";</script>",
                                "text/html", "utf-8", null);
                    } else {
                        Map extraHeaders = new HashMap();
                        extraHeaders.put("Referer", "https://m-patient.xiaohudaojia.com");
//                        if (num < 1) {
                        //second reload
                        wv.loadUrl(url, extraHeaders);
                        Log.e(TAG, "extraHeaders======${extraHeaders.size}");
//                            num++;
//                        }
                    }
                    return true;
                }
            } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
//                runOnUiThread(new Runnable()
//                {
//                    @Override
//                    public void run()
//                    {
                Toast.makeText(MainActivity.this, "请先下载相应App程序！", Toast.LENGTH_SHORT).show();
//                    }
//                });
                return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
            }
            //处理http和https开头的url
            wv.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView webView, String s, Bitmap bitmap)
        {
            super.onPageStarted(webView, s, bitmap);
        }

        @Override
        public void onPageFinished(WebView webView, String s)
        {
            super.onPageFinished(webView, s);
        }
    }

    public static final int REC_REQUESTCODE = 1;

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //判断事件完成，就是选择完图片
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (requestCode == REC_REQUESTCODE && resultCode == Activity.RESULT_OK) {
                Uri uri = null;
                if (data != null) {
                    uri = data.getData();
                    //拿到Uri  web回调只需要uri 所以转成绝对地址什么的是没有意义的
                    if (mFilePathCallback != null) {
                        Uri[] uris = new Uri[1];
                        uris[0] = uri;
                        mFilePathCallback.onReceiveValue(uris);//回调
                    } else {
                        mUploadMessage.onReceiveValue(uri);//或者另一种回调
                    }
                    mFilePathCallback = null;
                    mUploadMessage = null;
                }
            }
        } catch (Exception ex) {

        } finally {
            //重点来了 ！！！一次按钮点击 唤起事件后 无论你是否选择了文件  最后结束操作都必须调用以下内容 否则按钮就会出现只能点一次的现象，点击第二次就会无反应，
            if (mFilePathCallback != null) {
                Uri[] uris = new Uri[1];
                uris[0] = Uri.parse("");
                mFilePathCallback.onReceiveValue(uris);
                mFilePathCallback = null;
            }
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(Uri.parse(""));
                mUploadMessage = null;
            }
        }

        switch (requestCode) {
            case 123://请求权限返回
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // 检查该权限是否已经获取
                    int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                    // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        // 提示用户应该去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else {
                        Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                        mLocationClient.startLocation();
                    }
                }
                break;
            case 789://调用相机返回
                //部分手机获取uri为空，则需要从bundle中获取Bitmap
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri == null) {
                        Bundle bundle = data.getExtras();
                        if (bundle != null) {
                            Bitmap bitmap = (Bitmap) bundle.get("data"); //get bitmap
                            Bitmap compressBitmap = compressImage(bitmap);
                            Log.d("it520", "bitmapToBase64被调了...");
                            String str = bitmapToBase64(compressBitmap);
                            setPlatformType(str);
                        }
                    } else {
                        Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath());
                        Bitmap compressBitmap = compressImage(bitmap);
                        Log.d("it520", "else中的bitmapToBase64被调了...");
                        String str = bitmapToBase64(compressBitmap);
                        setPlatformType(str);
                    }
                    mFilePathCallback = null;
                    mUploadMessage = null;
                }
//                try {
//                    Uri uri = null;
//                    if (data != null) {
//                        uri = data.getData();
//                        //拿到Uri  web回调只需要uri 所以转成绝对地址什么的是没有意义的
//                        mUploadMessage.onReceiveValue(uri);//回调
//                        mUploadMessage = null;
//                    }
//                } catch (Exception ex) {
//                } finally {
//                    //重点来了 ！！！一次按钮点击 唤起事件后 无论你是否选择了文件  最后结束操作都必须调用以下内容 否则按钮就会出现只能点一次的现象，点击第二次就会无反应，
//                    if (mUploadMessage != null) {
//                        mUploadMessage.onReceiveValue(Uri.parse(""));
//                        mUploadMessage = null;
//                    }
//                }
                break;
        }
    }

    public void setPlatformType(final String result)
    {
//        new Handler().postDelayed(new Runnable() {
//
//            @Override
//            public void run() {
//                //android调用H5代码
//                webview.loadUrl("javascript: cameraResult('"+ result.toString() + "')");
//            }
//        }, 1000);
        webview.post(new Runnable()
        {
            @Override
            public void run()
            {
                //android调用H5代码
                webview.loadUrl("javascript: cameraResult('" + result.toString() + "')");
            }
        });
    }

    /**
     * 注册权限申请回调
     *
     * @param requestCode  申请码
     * @param permissions  申请的权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    boolean c = shouldShowRequestPermissionRationale(permissions[1]);
                    if (!b || !c) {
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else {

                    }
//                        finish();
                } else {
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                    mLocationClient.startLocation();
                }
            }
        }
    }

    /**
     * 申请定位权限
     */
    private boolean requestPermission()
    {
        //判断Android版本是否大于23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            int i = ContextCompat.checkSelfPermission(this, permissions[0]);
//            int i = PermissionChecker.checkSelfPermission(this, permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (i != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                return false;
            } else {
                return true;
            }
        }
        return true;
    }

    /**
     * 申请相机权限
     */
    private boolean requestCameraPermission()
    {
        //判断Android版本是否大于23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            int i = ContextCompat.checkSelfPermission(this, permissions[1]);
//            int i = PermissionChecker.checkSelfPermission(this, permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (i != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                return false;
            } else {
                return true;
            }
        }
        return true;
    }

    /**
     * 开始提交请求权限
     */
    private void startRequestPermission()
    {
        ActivityCompat.requestPermissions(this, permissions, 321);
    }

    /**
     * 提示用户去应用设置界面手动开启权限
     */
    private void showDialogTipUserGoToAppSettting()
    {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this)
                .setCustomTitle(DialogTools.getDialgoTitleView(this, "部分权限不可用", R.mipmap.hintdialog))
                .setMessage("请在-应用设置-权限-中，打开相应权限，以保证应用正常使用")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        // 跳转到应用设置界面
                        goToAppSetting();
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
//                        finish();
                    }
                }).setCancelable(false);
        dialog = alertDialog.show();
//        dialog = new AlertDialog.Builder(this)
//                .setCustomTitle(DialogTools.getDialgoTitleView(this, "部分权限不可用", R.mipmap.hintdialog))
//                .setMessage("请在-应用设置-权限-中，打开相应权限，以保证应用正常使用")
//                .setPositiveButton("立即开启", new DialogInterface.OnClickListener()
//                {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which)
//                    {
//                        // 跳转到应用设置界面
//                        goToAppSetting();
//                    }
//                })
//                .setNegativeButton("取消", new DialogInterface.OnClickListener()
//                {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which)
//                    {
//                        dialog.dismiss();
////                        finish();
//                    }
//                }).setCancelable(false).show();
    }

    /**
     * 提示用户去应用设置界面手动开启定位权限
     */
    private void showDialogLocationPermissionGoToAppSettting()
    {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this)
                .setCustomTitle(DialogTools.getDialgoTitleView(this, "定位权限不可用", R.mipmap.hintdialog))
                .setMessage("请在-应用设置-权限-中，打开定位权限，以保证应用正常使用")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        // 跳转到应用设置界面
                        goToAppSetting();
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
//                        finish();
                        dialog.dismiss();
                    }
                }).setCancelable(false);
        dialog = alertDialog.show();
//        dialog = new AlertDialog.Builder(this)
//                .setCustomTitle(DialogTools.getDialgoTitleView(this, "定位权限不可用", R.mipmap.hintdialog))
//                .setMessage("请在-应用设置-权限-中，打开定位权限，以保证应用正常使用")
//                .setPositiveButton("立即开启", new DialogInterface.OnClickListener()
//                {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which)
//                    {
//                        // 跳转到应用设置界面
//                        goToAppSetting();
//                    }
//                })
//                .setNegativeButton("取消", new DialogInterface.OnClickListener()
//                {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which)
//                    {
////                        finish();
//                        dialog.dismiss();
//                    }
//                }).setCancelable(false).show();
    }

    /**
     * 跳转到当前应用的设置界面
     */
    private void goToAppSetting()
    {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 123);
    }

    /**
     * 图片压缩
     */
    public Bitmap compressImage(Bitmap image)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
//因为获取到的ByteArrayOutputStream大小基本为50几kb，所以不用压缩，所以以下代码注释掉
//        int options = 90;
//        while (baos.toByteArray().length / 1024 > 200) {// 循环判断如果压缩后图片是否大于200kb,大于继续压缩
//            baos.reset(); // 重置baos即清空baos
//            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options，把压缩后的数据存放到baos中
//            options -= 10;// 每次都减少10
//        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    /**
     * bitmap转base64
     */
    public static String bitmapToBase64(Bitmap bitmap)
    {
        String result = "data:image/png;base64,";//必须加上“data:image/png;base64”图片的数据格式H5才能识别出来
        ByteArrayOutputStream bos = null;
        try {
            if (null != bitmap) {
                bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);// 将bitmap放入字节数组流中
                bos.flush();// 将bos流缓存在内存中的数据全部输出，清空缓存
                bos.close();
                byte[] bitmapByte = bos.toByteArray();
                result += Base64.encodeToString(bitmapByte, Base64.DEFAULT);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Log.d("it520", "result=" + result);
        Log.d("it520", "size=" + bos.toByteArray().length / 1024);//获取ByteArrayOutputStream的大小，单位kb，
        return result;
    }

    /**
     * base64转Bitmap
     */
    public static Bitmap base64ToBitmap(String base64String)
    {
        byte[] bytes = Base64.decode(base64String, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return bitmap;
    }
}


